package com.sunwayworld.basemodule.rm.filemanagement.service.impl;

import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.rm.filemanagement.dao.LimsFilemanagementVersionDao;
import com.sunwayworld.basemodule.rm.filemanagement.bean.LimsFilemanagementVersionBean;
import com.sunwayworld.basemodule.rm.filemanagement.service.LimsFilemanagementVersionService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

@Repository
@GikamBean
public class LimsFilemanagementVersionServiceImpl implements LimsFilemanagementVersionService {

    @Autowired
    private LimsFilemanagementVersionDao limsFilemanagementVersionDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsFilemanagementVersionDao getDao() {
        return limsFilemanagementVersionDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsFilemanagementVersionBean limsFilemanagementVersion = jsonWrapper.parseUnique(LimsFilemanagementVersionBean.class);
        limsFilemanagementVersion.setId(ApplicationContextHelper.getNextIdentity());

        LimsFilemanagementVersionBean exists = this.selectFirstByFilter(
                SearchFilter.instance().match("fileId", limsFilemanagementVersion.getFileId()).filter(MatchPattern.EQ)
                        .match("versionCode", limsFilemanagementVersion.getVersionCode()).filter(MatchPattern.EQ));
        if (exists != null && exists.getId() != null) {
            throw new InvalidDataException(I18nHelper.getMessage("BASEMODULE.RM.FILEMANAGEMENTS.TIP.VERSIONCODE_EXISTS"));
        }

        getDao().insert(limsFilemanagementVersion);
        return limsFilemanagementVersion.getId();
    }

}
